package com.example.mybatisstudy1.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // key序列化方式
        template.setKeySerializer(StringRedisSerializer.UTF_8);

        //Jackson2JsonRedisSerializer 序列化方式 来代替自来的jdk序列化方式，因为后者会乱码
        Jackson2JsonRedisSerializer jack = new Jackson2JsonRedisSerializer(Object.class);

        /**
         * 使用objeck设置对象的类型为真实的对象类型 而不是hsash
         */
        ObjectMapper mapper = new ObjectMapper();
        // 启用默认类型推理，将类型信息作为属性写入JSON
        // 就是把对象的全类名写入json
        mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
//         将类型的信息作为属性传给json
        jack.setObjectMapper(mapper);

        template.setValueSerializer(jack);
        template.setHashKeySerializer(StringRedisSerializer.UTF_8);
        template.setHashValueSerializer(jack);

        return template;
    }




}